import { defineStore } from 'pinia'
import axios from 'axios'

export const useVideoStore = defineStore('video', {
  state: () => ({
    videos: [],
    videoTypes: [],
    videoCategories: [],
    currentVideo: null,
    loading: false,
    error: null
  }),

  getters: {
    popularVideos: (state) => {
      return [...state.videos].sort((a, b) => (b.like_count || 0) - (a.like_count || 0))
    },
    latestVideos: (state) => {
      return [...state.videos].sort((a, b) => new Date(b.video_time) - new Date(a.video_time))
    },
    getVideosByType: (state) => (typeId) => {
      return state.videos.filter(video => video.type_id === typeId)
    }
  },

  actions: {
    async fetchVideos(filters = {}) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get('http://localhost:3000/videos', { params: filters })
        this.videos = response.data
      } catch (error) {
        this.error = '获取视频列表失败'
        console.error('获取视频列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchVideoById(id) {
      this.loading = true
      this.error = null
      try {
        // 使用查询参数查询video_id
        const response = await axios.get('http://localhost:3000/videos', {
          params: { video_id: id }
        })
        if (response.data.length > 0) {
          this.currentVideo = response.data[0]
        } else {
          this.error = '视频不存在'
        }
      } catch (error) {
        this.error = '获取视频详情失败'
        console.error('获取视频详情失败:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchVideoTypes() {
      console.log('开始获取视频类型...')
      try {
        console.log('发送请求到: http://localhost:3000/videoTypes')
        const response = await axios.get('http://localhost:3000/videoTypes')
        console.log('获取视频类型成功:', response.data)
        this.videoTypes = response.data
        console.log('更新后的videoTypes状态:', this.videoTypes)
      } catch (error) {
        console.error('获取视频类型失败:', error.message)
        if (error.response) {
          console.error('响应状态:', error.response.status)
          console.error('响应数据:', error.response.data)
        } else if (error.request) {
          console.error('请求已发送但未收到响应:', error.request)
        }
        // 为了开发调试，直接使用模拟数据
        this.videoTypes = [
          { type_id: 1, type_name: '科技', type_desc: '科技相关内容' },
          { type_id: 2, type_name: '游戏', type_desc: '游戏相关内容' },
          { type_id: 3, type_name: '美食', type_desc: '美食相关内容' },
          { type_id: 4, type_name: '数码', type_desc: '数码产品相关内容' },
          { type_id: 5, type_name: '音乐', type_desc: '音乐相关内容' },
          { type_id: 6, type_name: '旅行', type_desc: '旅行相关内容' }
        ]
        console.log('使用模拟数据:', this.videoTypes)
      }
    },

    async fetchVideoCategories() {
      try {
        const response = await axios.get('http://localhost:3000/videoCategories')
        this.videoCategories = response.data
      } catch (error) {
        console.error('获取视频分类失败:', error)
      }
    },

    async fetchVideosByType(typeId, limit = 4) {
      try {
        const response = await axios.get('http://localhost:3000/videos', {
          params: { type_id: typeId }
        })
        return response.data.slice(0, limit)
      } catch (error) {
        console.error(`获取类型 ${typeId} 的视频失败:`, error)
        return []
      }
    },

    async searchVideos(keyword) {
      try {
        const response = await axios.get('http://localhost:3000/videos')
        // 在前端过滤，因为json-server的模糊搜索有限
        return response.data.filter(video => 
          video.video_title.toLowerCase().includes(keyword.toLowerCase())
        )
      } catch (error) {
        console.error('搜索视频失败:', error)
        return []
      }
    },

    async fetchVideoComments(videoId, page = 1, pageSize = 10) {
      try {
        const response = await axios.get('http://localhost:3000/comments', {
          params: { video_id: videoId }
        })
        // 简单分页处理
        const start = (page - 1) * pageSize
        const end = start + pageSize
        return {
          comments: response.data.slice(start, end),
          total: response.data.length
        }
      } catch (error) {
        console.error('获取视频评论失败:', error)
        return { comments: [], total: 0 }
      }
    },

    async addComment(videoId, content) {
      try {
        const userData = localStorage.getItem('userData');
        if (!userData) {
          return { success: false, message: '请先登录' };
        }
        const user = JSON.parse(userData);
        
        const newComment = {
          video_id: videoId,
          content,
          comment_time: new Date().toISOString(),
          user_id: user.user_id,
          like_count: 0
        }
        const response = await axios.post('http://localhost:3000/comments', newComment)
        return { success: true, comment: response.data }
      } catch (error) {
        console.error('添加评论失败:', error)
        // 模拟添加成功，确保前端可以正常显示
        return { 
          success: true, 
          comment: {
            comment_id: Date.now(),
            video_id: videoId,
            content,
            comment_time: new Date().toISOString(),
            user_id: JSON.parse(localStorage.getItem('userData'))?.user_id || 1,
            like_count: 0
          }
        }
      }
    },

    async fetchDanmakus(videoId) {
      try {
        const response = await axios.get('http://localhost:3000/danmakus', {
          params: { video_id: videoId }
        })
        return response.data
      } catch (error) {
        console.error('获取弹幕失败:', error)
        return []
      }
    },

    async addDanmaku(videoId, content, color, time) {
      try {
        const userData = localStorage.getItem('userData');
        if (!userData) {
          return { success: false, message: '请先登录' };
        }
        const user = JSON.parse(userData);
        
        const newDanmaku = {
          video_id: videoId,
          user_id: user.user_id,
          content,
          color,
          time,
          type: 'scroll',
          send_time: new Date().toISOString()
        }
        const response = await axios.post('http://localhost:3000/danmakus', newDanmaku)
        return { success: true, danmaku: response.data }
      } catch (error) {
        console.error('发送弹幕失败:', error)
        // 模拟发送成功，确保前端可以正常显示
        return { 
          success: true, 
          danmaku: {
            danmaku_id: Date.now(),
            video_id: videoId,
            user_id: JSON.parse(localStorage.getItem('userData'))?.user_id || 1,
            content,
            color,
            time,
            type: 'scroll',
            send_time: new Date().toISOString()
          }
        }
      }
    },

    async fetchRelatedVideos(videoId, limit = 6) {
      try {
        // 先获取当前视频信息
        const currentVideoResp = await axios.get('http://localhost:3000/videos', {
          params: { video_id: videoId }
        })
        
        if (currentVideoResp.data.length === 0) {
          return []
        }
        
        const currentVideo = currentVideoResp.data[0]
        const response = await axios.get('http://localhost:3000/videos')
        
        // 根据视频类型和分类推荐相关视频
        return response.data
          .filter(video => 
            video.video_id !== videoId && 
            (video.type_id === currentVideo.type_id || 
             video.category_id === currentVideo.category_id)
          )
          .slice(0, limit)
      } catch (error) {
        console.error('获取相关视频失败:', error)
        return []
      }
    }
  }
})